package jpb.module.rest.load;

import jpb.constant.Reply;
import jpb.constant.StatusCode;
import jpb.module.daomain.member.LoadMem;
import jpb.module.daomain.organize.Organize;
import jpb.module.service.load.LoadService;
import jpb.security.HandleToken;
import jpb.util.GetMemory;
import org.apache.catalina.connector.Response;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

/**
 * Created by haol on 2017/4/13.
 */
@RestController
@RequestMapping("/api/web/load")
public class LoadController {
        @Autowired
        private LoadService loadService;

        @Value("${spring.profiles.os}")
        private String OS;

        @Value("${spring.profiles.oid}")
        private String oid;

        private Logger logger = LoggerFactory.getLogger(LoadController.class);


        /**
         * @api {GET} /api/web/load/i/{oid}/down 下载组织模板
         * @apiGroup Load
         * @apiName downloadModule
         * @apiDescription 下载id为{oid}的组织上传需要的模板
         * @apiParamExample {json} 请求样例：
         * GET /api/web/load/i/organize_id/down
         */
        @RequestMapping(value = "/i/{oid}/down", method = RequestMethod.GET)
        public ResponseEntity<byte[]> downloadModule(@PathVariable String oid, HttpServletResponse response) {
                try {
                        if (loadService.getDepartmentSize(oid) == 0) {
                                response.setStatus(Response.SC_ACCEPTED);
                                return null;
                        }
                        String memory = GetMemory.MEMORY();

                        String fileName = oid + "模板.xls";
                        String[] head;
                        if (loadService.get(oid).getType() == 0) {
                                head = StatusCode.ORGANIZE_HEAD;
                        } else {
                                head = StatusCode.LEAGUER_HEAD;
                        }


                        loadService.buildExcel(oid, memory, fileName, head);
                        ResponseEntity<byte[]> responseEntity = loadService.download(memory + fileName, oid,"上传模板");
                        return responseEntity;
                } catch (Exception e) {
                        e.printStackTrace();
                        return null;
                }
        }


        /**
         * @api {GET} /api/web/load/i/{oid}/down/mem 下载组织成员信息
         * @apiGroup Load
         * @apiName downloadMsg
         * @apiDescription 下载id为{oid}的组织成员信息,包含是否注册,是否填写信息及详细信息
         * @apiParamExample {json} 请求样例：
         * GET /api/web/load/i/organize_id/down/mem
         */
        @RequestMapping(value = "/i/{oid}/down/mem", method = RequestMethod.GET)
        public ResponseEntity<byte[]> downloadMsg(@PathVariable String oid, HttpServletResponse response) {
                try {

                        String memory = GetMemory.MEMORY();

                        String fileName = oid + "成员信息.xls";
                        String[] head;
                      head = StatusCode.MEMBER_HEAD;

                        loadService.buildExcelConMem(oid, memory, fileName, head);
                        ResponseEntity<byte[]> responseEntity = loadService.download(memory + fileName, oid,"成员信息");
                        return responseEntity;
                } catch (Exception e) {
                        e.printStackTrace();
                        return null;
                }
        }




        /**
         * @api {POST} /api/web/load/upload 上传组织信息模板
         * @apiGroup Load
         * @apiName upload
         * @apiDescription 上传组织模板，含有编号和职称
         * @apiParamExample {json} 请求样例：
         * POST /api/web/load/upload
         * {
         * “file":"file.xls",
         * }
         * @apiSuccessExample {json} 返回样例:
         * {
         * "code":0,"msg":"请查看详情"
         * }
         */
        @RequestMapping(value = "/upload", method = RequestMethod.POST)
        public String upload(MultipartFile file, HttpServletRequest request, HttpServletResponse response) {
                String memory = GetMemory.MEMORY();

                String uploadDir = memory + file.getOriginalFilename();
                logger.info("上传文件路径为：{}", uploadDir);
                String[] head;
                PrintWriter out = null;
                try {
                        response.setContentType("text/html; charset=UTF-8");
                        out = response.getWriter();
                        loadService.uploadFiles(file, memory);
                        File justFile = new File(uploadDir);
                        FileInputStream inputStream = new FileInputStream(justFile);
                        HSSFWorkbook workbook = new HSSFWorkbook(inputStream);
                        String oid = loadService.getFileOid(workbook);

                        HandleToken handleToken = new HandleToken();
                        String mid = handleToken.getTokenOid(request);

                        boolean state = loadService.checkPow(mid, oid);


                        if (state) {
                                logger.info("开始处理上传内容");
                                Organize organize = loadService.get(oid);
                                if (organize.getType() == 2) {
                                        head = StatusCode.LEAGUER_HEAD;
                                } else {
                                        head = StatusCode.ORGANIZE_HEAD;
                                }
                                List<LoadMem> members = loadService.handleExcel(workbook, head);
                                logger.info("处理上传内容结束");

                        } else {
                                logger.error("该用户没有权限");
                                return new Reply(1, "你没有权限").toJson();
                        }
                } catch (IOException e) {
                        logger.error(e.getMessage());
                } catch (Exception e) {
                        e.printStackTrace();
                        logger.error(e.getMessage());
                } finally {
                        if (out != null) {
                                out.flush();
                                out.close();
                        }
                        return null;
                }

        }

        /**
         * @api {POST} /api/web/load/bitch-member 上传注册成员
         * @apiGroup Load
         * @apiName uploadMember
         * @apiDescription 批量注册成员信息，内含编号，姓名，电话,地址和介绍
         * @apiParamExample {json} 请求样例：
         * POST /api/web/load/bitch-member
         * {
         * “file":"file.xls",
         * }
         * @apiSuccessExample {json} 返回样例:
         * {
         * "code":0,"msg":"请查看详情"
         * }
         */
        @RequestMapping(value = "/bitch-member", method = RequestMethod.POST)
        public String uploadMember(MultipartFile file,
                                   HttpServletRequest request, HttpServletResponse response) {
                String memory = GetMemory.MEMORY();

                String uploadDir = memory + file.getOriginalFilename();
                logger.info("上传文件路径为：{}", uploadDir);
                PrintWriter out = null;
                Reply<List<LoadMem>> reply = null;
                String[] head = StatusCode.REGISTER_HEAD;
                try {
                        response.setContentType("text/html; charset=UTF-8");
                        out = response.getWriter();
                        loadService.uploadFiles(file, memory);
                        File justFile = new File(uploadDir);
                        FileInputStream inputStream = new FileInputStream(justFile);
                        HSSFWorkbook workbook = new HSSFWorkbook(inputStream);
                        boolean state = true;
                        if (state) {
                                logger.info("开始处理上传内容");
                                List<LoadMem> members = loadService.handleExcelReg(workbook, head);
                                logger.info("处理上传内容结束");
                                reply = new Reply<List<LoadMem>>(0, "请查看详情", members);

                        } else {
                                logger.error("该用户没有权限");
                                reply = new Reply(1, "你没有权限");
                        }
                } catch (Exception e) {
                        e.printStackTrace();
                        logger.error(e.getMessage());
                } finally {
                        if (out != null) {
                                out.flush();
                                out.close();
                        }
                        logger.info(reply.toJson());
                        return null;
                }
        }

        /**
         * @api {GET} /api/web/load/bitch-member 下载批量注册模板
         * @apiGroup Load
         * @apiName downloadRegister
         * @apiDescription 下载批量注册模板
         * @apiParamExample {json} 请求样例：
         * GET /api/web/load/bitch-member
         */
        @RequestMapping(value = "/bitch-member", method = RequestMethod.GET)
        public ResponseEntity<byte[]> downloadRegister() {
                try {
                        String memory = GetMemory.MEMORY();

                        String fileName = oid + ".xls";
                        String[] head = StatusCode.REGISTER_HEAD;

                        loadService.buildExcel(memory, fileName, head);
                        ResponseEntity<byte[]> responseEntity = loadService.download(memory + fileName, oid,"注册模板");
                        return responseEntity;
                } catch (Exception e) {
                        e.printStackTrace();
                        return null;
                }
        }
        
        



}
